/*
 * @Description: 
 * @Version: 
 * @Autor: LiChuang
 * @Date: 2023-11-13 22:38:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-11-22 19:52:34
 */
import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import CryptoJS from 'crypto-js';
import { useUserStoreHook } from "@/store/modules/user";
import {formatTime} from '@/utils/index'

const token = useStorage("accessToken", "");
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_TARGET_URL,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    config.headers['Accept-Language'] = localStorage.getItem('language') == 'en'?'en-US':localStorage.getItem('language') == 'zh-cn'?'zh-CN':'zh-HK'
    if(localStorage.getItem('Skey')){
      const nowdate = new Date();
      let url = config.url 
      const hash = CryptoJS.HmacSHA1(`${url}|${formatTime(nowdate.valueOf(),'yyyy-MM-dd HH:mm:ss')}`, localStorage.getItem('Skey'));
      const sign = CryptoJS.enc.Hex.stringify(hash);
      (config.headers)['REQUEST-TIME'] =  formatTime(nowdate.valueOf(),'yyyy-MM-dd HH:mm:ss');
      (config.headers)['REQUEST-SIGN'] =  sign;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if(response.headers.authorization){
      token.value = 'Malaifeng '+ response.headers.authorization; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
    }
    if(response.headers.skey){
			localStorage.setItem('Skey', response.headers.skey)
		}
    const { code, message } = response.data;
    if (code === "200") {
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }
    // ElMessage.success(message);
    return Promise.resolve(response.data);
  },
  (error: any) => {
    if (error.response.data) {
      const { code, message } = error.response.data;
      // token 过期,重新登录
      if (code === "401") {
        ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).then(() => {
          const userStore = useUserStoreHook();
          userStore.resetToken().then(() => {
            location.reload();
          });
        });
      } else {
        ElMessage.error(message || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
